package cn.itsource.crm.web.controller;

import cn.itsource.AjaxResult;
import cn.itsource.crm.domain.MyUser;
import cn.itsource.crm.web.util.UserContext;
import io.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.HashMap;

/**
 * 常见的状态码：
 *      200  成功
 *      400  传递的参数类型转换异常
 *      500  后台出现问题了
 *      304  缓存
 *      302  你的请求被拦截了
 */
@Controller
@CrossOrigin
@Api(tags = "登录接口类")
public class LoginController {
    /**
     * 如果你的请求是/login并且是post提交，那就走此方法
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult login(@RequestBody MyUser user){
        //获取到当前用户
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        //如果没有认证
        if(!subject.isAuthenticated()){
            //把用户名和密码封装成一个token对象
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            try {
                //开始认证
                subject.login(token);
                //把当前登陆用户放到session中（当你把值存放到shiro的session中之后，它会自动同步到httpsession中）
                UserContext.setSession((MyUser) subject.getPrincipal());
                AjaxResult result = new AjaxResult();
                MyUser myUser = (MyUser) subject.getPrincipal();
                myUser.setPassword(null);
                //手动把sessionid 返回到前台
                Serializable sessionId = subject.getSession().getId();
                HashMap mp = new HashMap();
                mp.put("token",sessionId);
                mp.put("user",myUser);
                result.setData(mp);
                return result;
            } catch (UnknownAccountException e) {
                e.printStackTrace();
                return new AjaxResult(false, "账号不存在!!");
            }catch (IncorrectCredentialsException e){
                e.printStackTrace();
                return new AjaxResult(false, "密码错误!!");
            }catch (Exception e){
                e.printStackTrace();
                return new AjaxResult(false, "网络繁忙,请稍后再试!!!");
            }
        }
        return new AjaxResult();
    }
}
